package com.zrkj.interceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class UserContextHolder {

    private ThreadLocal<Map<String, String>> threadLocal;

    private UserContextHolder() {

        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * @param
     * @return net.izd.common.util.UserContextHolder
     * @author Alvin
     * @description 创建实例
     * @date 2019/11/16 9:39
     */
    public static UserContextHolder getInstance() {

        return SingletonHolder.S_INSTANCE;
    }

    /**
     * @param
     * @author alvin
     * @description 静态内部类单例模式
     * @date 2019/11/16 9:40
     * @return
     */
    private static class SingletonHolder {

        private static final UserContextHolder S_INSTANCE = new UserContextHolder();
    }

    /**
     * @param map
     * @return void
     * @author alvin
     * @description 用户上下文中放入信息
     * @date 2019/11/16 9:41
     */
    public void setContext(Map<String, String> map) {
        threadLocal.set(map);
    }

    /**
     * @param
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author alvin
     * @description 获取上下文中的信息
     * @date 2019/11/16 9:42
     */
    public Map<String, String> getContext() {
        return threadLocal.get();
    }

    /**
     * @param
     * @return java.lang.String
     * @author alvin
     * @description 获取上下文中的用户名
     * @date 2019/11/16 9:43
     */
    public String getUserId() {
        return Optional.ofNullable(threadLocal.get())
                .orElse(new HashMap<>())
                .get("userId");
    }


    public String getUserName() {
        return Optional.ofNullable(threadLocal.get())
                .orElse(new HashMap<>())
                .get("userName");
    }

    /**
     * @param
     * @return void
     * @author alvin
     * @description 清空上下文
     * @date 2019/11/16 9:43
     */
    public void clear() {
        threadLocal.remove();
    }
}
